package com.mj.boot.aspect;

import com.alibaba.fastjson.JSONObject;
import com.mj.boot.base.pojo.WebLog;
import com.mj.boot.config.GearProperties;
import com.mj.boot.mapper.WebLogMapper;
import com.mj.boot.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 记录请求参数日志，耗时等信息
 *
 * @author zmj
 * @date 2021-08-30 13:50
 */
@Slf4j
@Aspect
@Component
@ConditionalOnProperty(value = "gear.webLog.enabled", havingValue = "true", matchIfMissing = true)
public class WebLogAspect {

    @Resource
    private WebLogMapper webLogMapper;

    @Resource
    private GearProperties gearProperties;

    private boolean write;

    @PostConstruct
    public void loadGearProperties() {
        this.write = gearProperties.getWebLog().isWrite();
    }

    /**
     * todo 获取项目包名作为切入点
     * 以 com.zmj.controller包下定义的所有请求为切入点
     */
    @Pointcut("execution( * com.zmj.controller..*.*(..))")
    public void webLog() {
    }

    /**
     * 环绕织入
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String requestType = request.getMethod();
        String uri = request.getRequestURI();
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String method = joinPoint.getSignature().getName();

        log.info(" 请求方式:[{}], URI: [{}] Class Name: [{}], Method: [{}]", requestType, uri, className, method);
        String requestJson = null;
        try {
            if (requestType.equalsIgnoreCase("post")) {
                Map<String, Object> fieldsName = getFieldsName(joinPoint);
                for (String key : fieldsName.keySet()) {
                    if (!HttpServletRequest.class.isInstance(fieldsName.get(key))) {
                        requestJson = JSONObject.toJSONString(fieldsName.get(key));
                        log.info("Request Body: [{}]", requestJson);
                    }
                }
            }
            if (requestType.equalsIgnoreCase("get")) {
                if (!CollectionUtils.isEmpty(request.getParameterMap())) {
                    requestJson = JSONObject.toJSONString(request.getParameterMap());
                    log.info("Request Params: [{}]", requestJson);
                }
            }
        } catch (Exception e) {
            log.error("请求参数解析异常 Class is [{}], Method: [{}] , error is ", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e);
        }
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();//若controller执行异常，后面则不执行,也不会记录
        String responseJson = JSONObject.toJSONString(result);
        long timeConsuming = (System.currentTimeMillis() - startTime) / 1000;

        log.info("Response Json is: [{}] ,method use time :[{}] ms", responseJson, timeConsuming);

        if (write) {
            webLogMapper.insert(new WebLog().setClassStr(className).setMethod(method).setUri(uri).setRequestType(requestType)
                    .setIp(IPUtil.getIpAddress(request)).setRequestJson(requestJson)
                    .setResponseJson(responseJson).setTimeConsuming(timeConsuming));
        }
        return result;
    }

    /**
     * 封装参数列表
     */
    private static Map<String, Object> getFieldsName(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String[] parameterNames = pnd.getParameterNames(method);
        Map<String, Object> paramMap = new HashMap<>(32);
        for (int i = 0; i < parameterNames.length; i++) {
            paramMap.put(parameterNames[i], args[i]);
        }
        return paramMap;
    }
}
